<?php

namespace Admin\Controller;
use Home\Api\V10\Sms;
/**
 * 短信管理控制器
 * @since   2017-05-19
 * @author  wangyining
 */
class SmsController extends BaseController {

    //请求消息管理
    public function request(){
        $data = I('post.','');
        $startTim=strtotime($data['startTime']);
        $endTime=strtotime($data['endTime']);
        $sql = " 1=1 ";
        if (!empty($data)) {
            if($data['company_name'])  $sql .= " and company_name like '%".$data['company_name']."%' ";
            if($data['mobile'])         $sql .= " and mobile like '%".$data['mobile']."%' ";
            if($data['content'])        $sql .= " and content like '%".$data['content']."%' ";
            if($data['startTime'])      $sql .= " and receive_time >'".$startTim."' ";
            if($data['endTime'])        $sql .= " and receive_time <'".$endTime."' ";
            if($data['type'])           $sql .= " and type='".$data['type']."' ";
            if($data['status'])         $sql .= " and `status`='".$data['status']."' ";
        }

        $dataAll = D("ApiSmsqueue")->field("api_smsqueue.*,api_company.company_name")->join("api_company on api_smsqueue.c_id=api_company.id")->where($sql)->ORDER("receive_time desc")->select();
        $this->assign('data',$dataAll);
        $this->assign('info',$data);
        $this->display();
    }

    //请求消息管理--立即手动发送
    public function manualSend(){
        $id = I('post.id');
        $valueData=D('ApiItem')->where(array('key'=>'sms'))->find();
        $values=unserialize($valueData['value']);
        $data=D('ApiSmsqueue')->where(array('id'=>$id))->find();

        $detail['action']  ="sendOnce";
        $detail['m']       = $data['mobile'];
        $detail['c']       = $data['content'];
        $detail['t']       = $data['timing'];
        $detail['ac']      = $values['ac'];
        $detail['authkey']= $values['authkey'];
        $detail['cgid']    = $values['cgid'];
        $detail['csid']    = $values['csid'];

        if($data['usertype']=='1'){//发送短信给单用户
            $detail['action']  ="sendOnce";
            $xml = postSMS($detail);
            $re = simplexml_load_string(utf8_encode($xml));
            $res = trim($re['result']);
        }elseif($data['usertype']=='2'){//发送短信给多用户
            $detail['action']  ="sendBatch";
            $n=count(explode(',',trim($detail['m'],',')));
            $content="";
            for($i=1;$i<=$n;$i++){
                $content .= $detail['c']."{|}";
            };
            $detail['c']=trim($content,"{|}");
            $xml = postSMS($detail);
            $re = simplexml_load_string(utf8_encode($xml));
            $res = trim($re['result']);
        }

        $data['send_time'] = time();
        $data['adminid'] = $_SESSION['uid'];
        unset($data['id']);
        if ($res == '1') {  //成功
            $data['status'] = '1';
            D("ApiSmsrecords")->add($data);
            D("ApiSmsqueue")->where("id='$id'")->save(array('status'=>'1'));
            $this->ajaxSuccess('发送成功');
        }else{
            $data['status'] = '2';
            D("ApiSmsrecords")->add($data);
            $this->ajaxError('发送失败');
        }
    }

    //删除请求记录
    public function delRequest() {
        $id = I('post.id');
        $res = D('ApiSmsqueue')->where(array('id' => $id))->delete();
        if ($res === false) {
            $this->ajaxError('操作失败');
        } else {
            $this->ajaxSuccess('操作成功');
        }
    }

    //发送记录管理
    public function send() {
        $data = I('post.','');
        $startTim=strtotime($data['startTime']);
        $endTime=strtotime($data['endTime']);
        $sql = " 1=1 ";
        if (!empty($data)) {
            if($data['company_name'])  $sql .= " and company_name like '%".$data['company_name']."%' ";
            if($data['mobile'])         $sql .= " and mobile like '%".$data['mobile']."%' ";
            if($data['content'])        $sql .= " and content like '%".$data['content']."%' ";
            if($data['startTime'])      $sql .= " and send_time >'".$startTim."' ";
            if($data['endTime'])        $sql .= " and send_time <'".$endTime."' ";
            if($data['type'])           $sql .= " and `type`='".$data['type']."' ";
            if($data['status'])         $sql .= " and `status`='".$data['status']."' ";
        }

        $dataAll = D("ApiSmsrecords")->field("api_smsrecords.*,api_company.company_name")->join("api_company on api_smsrecords.c_id=api_company.id")->where($sql)->ORDER("send_time desc")->select();
        $user = D("ApiUser");
        foreach ($dataAll as $k => $v) {
            if ($v['adminid']) {
                $res = $user->field("username")->where("id='".$v['adminid']."'")->find();
                $dataAll[$k]['adminName'] = $res['username'];
            }else{
                $dataAll[$k]['adminName'] = '---';
            }
        }
        $this->assign('data',$dataAll);
        $this->assign('info',$data);
        $this->display();
    }

    //发送记录管理--立即手动发送
    public function recordSend(){
        $id = I('post.id');
        $data=D('ApiSmsrecords')->where(array('id'=>$id))->find();
        $valueData=D('ApiItem')->where(array('key'=>'sms'))->find();
        $values=unserialize($valueData['value']);
        $detail['m']       = $data['mobile'];
        $detail['c']       = $data['content'];
        $detail['ac']      = $values['ac'];
        $detail['authkey']= $values['authkey'];
        $detail['cgid']    = $values['cgid'];
        $detail['csid']    = $values['csid'];
        if($data['usertype']=='1'){//发送短信给单用户
            $detail['action']  ="sendOnce";
            $xml = postSMS($detail);
            $re = simplexml_load_string(utf8_encode($xml));
            $res = trim($re['result']);
        }elseif($data['usertype']=='2'){//发送短信给多用户
            $detail['action']  ="sendBatch";
            $n=count(explode(',',trim($detail['m'],',')));
            $content="";
            for($i=1;$i<=$n;$i++){
                $content .= $detail['c']."{|}";
            };
            $detail['c']=trim($content,"{|}");
            $xml = postSMS($detail);
            $re = simplexml_load_string(utf8_encode($xml));
            $res = trim($re['result']);
        }

        if ($res == '1') {
            $data['send_time'] = time();
            $data['adminid'] = $_SESSION['uid'];
            unset($data['id']);
            $data['status'] = '1';
            D("ApiSmsrecords")->where("id='$id'")->save($data);
            $this->ajaxSuccess('发送成功');
        }else{
            $this->ajaxError('发送失败');
        }
    }

    //删除发送记录
    public function delSend(){
        $id = I('post.id');
        $res = D('ApiSmsrecords')->where(array('id' => $id))->delete();
        if ($res === false) {
            $this->ajaxError('操作失败');
        } else {
            $this->ajaxSuccess('操作成功');
        }
    }

    //配置
    public function configuration(){
        if( IS_POST ){
            $data = I('post.');
            $detail['ac']=trim($data['ac']);
            $detail['authkey']=trim($data['authkey']);
            $detail['cgid']=trim($data['cgid']);
            $detail['csid']=trim($data['csid']);
            $detail['num']=trim($data['num']);
            $sms=D('ApiItem')->where(array('key'=>'sms'))->find();
            if($sms){
                $sms['key']='sms';
                $sms['value']=serialize($detail);
                $res = D('ApiItem')->where(array('key'=>$sms['key']))->save($sms);
                if( $res === false ){
                    $this->ajaxError('操作失败');
                }else{
                    $this->ajaxSuccess('添加成功');
                }
            }else{
                $sms['key']='sms';
                $sms['value']=serialize($detail);
                $sms['app_id']=0;
                $res = D('ApiItem')->add($sms);
                if( $res === false ){
                    $this->ajaxError('操作失败');
                }else{
                    $this->ajaxSuccess('添加成功');
                }
            }
        }else{
            $sms=D('ApiItem')->where(array('key'=>'sms'))->find();
            $this->assign('sms',unserialize($sms['value']));
            $this->display();
        }
    }

    //短信充值记录
    public function rechargeRecord(){
        $data = I('post.','');
        $startTim=strtotime($data['startTime']);
        $endTime=strtotime($data['endTime']);
        $sql = " 1=1 ";
        if (!empty($data)) {
            if($data['company_name'])  $sql .= " and company_name like '%".$data['company_name']."%' ";
            if($data['startNum'])       $sql .= " and recharge_num >= '".$data['startNum']."' ";
            if($data['endNum'])         $sql .= " and recharge_num <= '".$data['endNum']."' ";
            if($data['startTime'])      $sql .= " and addtime >'".$startTim."' ";
            if($data['endTime'])        $sql .= " and addtime <'".$endTime."' ";
            if($data['username'])       $sql .= " and username like'%".$data['username']."%' ";
        }
        $list = D('ApiRechargerecords')->field('api_rechargerecords.*,api_company.company_name,api_user.username')->join('api_company ON api_rechargerecords.c_id = api_company.id')->join('api_user ON api_rechargerecords.adminid=api_user.id')->where($sql)->ORDER('addtime desc')->select();
        $this->assign('list',$list);
        $this->assign('info',$data);
        $this->display();
    }

    //删除充值记录
    public function delRecharge(){
        $id = I('post.id');
        $res = D('ApiRechargerecords')->where(array('id' => $id))->delete();
        if ($res === false) {
            $this->ajaxError('操作失败');
        } else {
            $this->ajaxSuccess('操作成功');
        }
    }

    //给商户充值余额
    public function recharge(){
        if( IS_GET ){
            $id = I('get.id');
            $detail =D('ApiSmsmanage')->where(array('id' => $id))->find();
            $company=D('ApiCompany')->where(array('id' => $detail['c_id']))->find();
            $detail['company_name'] = $company['company_name'];

            $valueData=D('ApiItem')->where(array('key'=>'sms'))->find();
            $values=unserialize($valueData['value']);
            $item['action']='getBalance';
            $item['ac']      = $values['ac'];
            $item['authkey']= $values['authkey'];
            $xml = postSMS($item);
            $re=simplexml_load_string(utf8_encode($xml));
            $res=$re->Item;
            $sms_num=$res['remain'];
            $this->assign('sms_num',$sms_num*10);
            $this->assign('detail', $detail);
            $this->display('recharge');
        }elseif( IS_POST ){
            $data = I('post.');
            if($data['recharge_num']>$data['sms_num']){
                $this->ajaxError('充值量大于平台余额');
            }
            $recharge['c_id']  =  $data['c_id'];
            $recharge['recharge_num'] = $data['recharge_num'];
            $recharge['adminid'] =$_SESSION['uid'];
            $recharge['addtime'] = time();
            $res = D('ApiRechargerecords')->add($recharge);

            $res =D('ApiSmsmanage')->where(array('id' => $data['id']))->find();
            $data['sms_totalnum'] = $data['recharge_num']+$res['sms_totalnum'];
            $data['surplus_num']  = $data['recharge_num']+$res['surplus_num'];
            $data['updatetime']   = time();
            $res = D('ApiSmsmanage')->where(array('id' => $data['id']))->save($data);
            if( $res === false ){
                $this->ajaxError('操作失败');
            }else{
                $this->ajaxSuccess('添加成功');
            }
        }
    }

    //商户短信管理
    public function manage(){
        $valueData=D('ApiItem')->where(array('key'=>'sms'))->find();
        $values=unserialize($valueData['value']);
        $detail['action']='getBalance';
        $detail['ac']      = $values['ac'];
        $detail['authkey']= $values['authkey'];
        $xml = postSMS($detail);
        $re=simplexml_load_string(utf8_encode($xml));
        $item=$re->Item;
        $num=sprintf('%.1f',$item["remain"]);
        $list = D('ApiSmsmanage')->field('api_smsmanage.*,api_company.company_name')->join('api_company ON api_smsmanage.c_id = api_company.id')->select();
        $this->assign('list', $list);
        $this->assign('sms_num',$num*10);
        $this->display();
    }
}
